package com.ncet.circuit.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.ncet.circuit.shared.LoginInfo;

public class Circuit implements EntryPoint
{
	@Override
	public void onModuleLoad()
	{
		LoginServiceAsync async = ( LoginServiceAsync ) GWT.create( LoginService.class );
		
		String successUrl;
		
		if ( GWT.isProdMode() )
			successUrl =  "http://ldsimulator.appspot.com/Simulator.html";
		else
			successUrl =  "http://127.0.0.1:8888/Simulator.html?gwt.codesvr=127.0.0.1:9997";
		
		String failureUrl;
		
		if ( GWT.isProdMode() )
			failureUrl =  "http://ldsimulator.appspot.com" ;
		else
			failureUrl =  "http://127.0.0.1:8888/Circuit.html?gwt.codesvr=127.0.0.1:9997" ;
		
		async.login( successUrl, failureUrl, new AsyncCallback<LoginInfo>()
		{
			public void onFailure( Throwable caught )
			{
				caught.printStackTrace();
			}

			public void onSuccess( LoginInfo result )
			{
				loadLogin( result );
			}
		} );
	}

	public static native void redirect( String url )/*-{
		$wnd.location = url;
	}-*/;
	
	native void setImageHref(String loginUrl )/*-{
		$wnd.loginUrl = loginUrl;
	}-*/;
	
	private void loadLogin( final LoginInfo result )
	{
		setImageHref(result.getLoginUrl());
		loadLogout();
	}

	public static void logout()
	{
		LoginServiceAsync async = ( LoginServiceAsync ) GWT.create( LoginService.class );
		
		String href;
		if ( GWT.isProdMode() )
			href =  "http://ldsimulator.appspot.com" ;
		else
			href =  "http://127.0.0.1:8888/Circuit.html?gwt.codesvr=127.0.0.1:9997" ;
		
		async.logout( href, new AsyncCallback<String>(){
			public void onFailure( Throwable caught )
			{
				caught.printStackTrace();
			}

			public void onSuccess( String result )
			{
				redirect( result );
			}
		} );
	}
	
	public native void loadLogout()/*-{
		$wnd.logoutGmail = function(amt, intRate, term) {
          return @com.ncet.circuit.client.Circuit::logout()();
       }
	}-*/;
}
